package com.mao.handler;

import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by kechelle on 2020/8/4 10:37
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    //获取日志对象
    private final Logger  logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)   //这个方法可以处理Exception级别的异常
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        logger.error("Request URL : {},Exception : {}",request.getRequestURL(),e);

        //定义了特定注解的异常处理类需要抛出自定义异常
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
        }
        ModelAndView model = new ModelAndView();
        model.addObject("url",request.getRequestURL());
        model.addObject("exception",e);
        model.setViewName("error/error");
        return model;
    }

}
